<template>
  <div class="form_warp">
    <u-form ref="uForm" :model="form" label-position="top">
      <view v-for="fKey in sortedKeys" :key="fKey" style="position: relative;">
        <u-form-item
          :label="formConfig[fKey]['label']"
          :prop="fKey"
          :required="formConfig[fKey]['isRequired']"
        >
          <u-input
            v-if="inputTypeList.includes(formConfig[fKey]['type']) && !formConfig[fKey].customize.disabled"
            :disabled="formConfig[fKey].customize.disabled"
            :placeholder="formConfig[fKey].customize.placeholder"
            :value="form[fKey]"
            :type="formConfig[fKey]['type']"
            @input="onInputChange($event, fKey)"
            @click="onInputFocused($event, fKey)"
          />
          <u-input
            v-else-if="selectTypeList.includes(formConfig[fKey]['type']) && !formConfig[fKey].customize.disabled"
            :value="form[fKey]"
            :placeholder="formConfig[fKey].customize.placeholder"
            :select-open="formConfig[fKey]['visible']"
            type="select"
            @click="onSelectClick(fKey)"
          />
          <u-input
            v-else-if="formConfig[fKey].prop==='probationDays' && !formConfig[fKey].customize.disabled"
            :value="form[fKey]"
            :select-open="formConfig[fKey]['visible']"
            :placeholder="formConfig[fKey].customize.placeholder"
            type="number"
            @click="onSelectClicks(fKey)"
          />
          <u-input
            v-else-if="formConfig[fKey]['type'] === 'ganged' && !formConfig[fKey].customize.disabled"
            :value="form[fKey]"
            :placeholder="formConfig[fKey].customize.placeholder"
            :select-open="formConfig[fKey]['visible']"
            type="select"
            @click="onSelectClicks(fKey)"
          />
          <u-input
            v-else-if="formConfig[fKey]['type'] === 'area' && !formConfig[fKey].customize.disabled"
            :value="form[fKey]"
            :placeholder="formConfig[fKey].customize.placeholder"
            :select-open="formConfig[fKey]['visible']"
            type="select"
            @click="onSelectClick(fKey)"
          />

          <u-input
            v-else-if="formConfig[fKey]['type'] === 'date' && !formConfig[fKey].customize.disabled"
            :value="form[fKey]"
            :placeholder="formConfig[fKey].customize.placeholder"
            :select-open="formConfig[fKey]['visible']"
            type="select"
            @click="onSelectClick(fKey)"
          />

          <!-- 图片上传 -->
          <Appendix
            v-else-if="formConfig[fKey]['type'] === 'upload' && !formConfig[fKey].customize.disabled"
            :count="1"
            :maxCount="formConfig[fKey].customize.maxCount"
            :value="form[fKey]"
            @change="onSelectCancels($event, fKey)"
          />
          <span v-else style="color: rgba(0,0,0,.25);">{{ form[fKey] }}</span>
        </u-form-item>

        <u-select
          v-if="selectTypeList.includes(formConfig[fKey]['type'])"
          :key="`select_${fKey}`"
          :value="formConfig[fKey]['visible']"
          :list="buildSelectList(fKey)"
          :placeholder="formConfig[fKey].customize.placeholder"
          :mask-close-able="false"
          :confirmColor="$store.settings.theme"
          mode="single-column"
          @confirm="onSelectConfirm($event, fKey)"
          @cancel="onSelectCancel(fKey)"
        />
        <u-select
          v-else-if="formConfig[fKey]['type'] === 'ganged'"
          :key="`ganged_${fKey}`"
          v-model="show"
          :value="formConfig[fKey]['visible']"
          :list="list"
          :placeholder="formConfig[fKey].customize.placeholder"
          :mask-close-able="false"
          :confirmColor="$store.settings.theme"
          mode="mutil-column"
          @confirm="onSelectConfirms($event, fKey)"
          @cancel="onSelectCancel(fKey)"
        />
        <AreaPicker
          v-else-if="formConfig[fKey]['type'] === 'area'"
          :key="`area_${fKey}`"
          :default-value="form[fKey]"
          :placeholder="formConfig[fKey].customize.placeholder"
          :value="formConfig[fKey]['visible']"
          @confirm="onAreaPickerConfirm($event, fKey)"
          @cancel="onSelectCancel(fKey)"
        />
        <u-picker
          v-else-if="formConfig[fKey]['type'] === 'date'"
          :key="`date_${fKey}`"
          :value="formConfig[fKey]['visible']"
          :placeholder="formConfig[fKey].customize.placeholder"
          :params="dateParams"
          :default-time="form[fKey]"
          :mask-close-able="false"
          :confirmColor="$store.settings.theme"
          mode="time"
          @confirm="onDatePickerConfirm($event, fKey)"
          @cancel="onSelectCancel(fKey)"
        />
         <u-button
          style="position: absolute;right: -27px;bottom:14px;"
          v-if="formConfig[fKey].prop==='probationDays'"
          slot="right"
          size="mini"
        >天</u-button>
      </view>
    </u-form>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import { selectTypeList, inputTypeList } from "@/components/XqForm/utils";
import AreaPicker from "@/components/XqForm/components/areaPicker";
import Appendix from "./appendix";
import dayjs from "dayjs";
export default {
  name: "",
  components: {
    AreaPicker,
    Appendix
  },
  mixins: [],
  props: {
    isShow: {
      type: Boolean,
      default: true
    },
    form: {
      type: Object,
      default: () => {}
    },
    sortedKeys: {
      type: Array,
      default: () => []
    },
    formConfig: {
      type: Object,
      default: () => {}
    },
    rules: {
      type: Object,
      default: () => {}
    },
    selectMap: {
      type: Object,
      default: () => {}
    },
    dynamicData: {
      type: Object,
      default: () => {}
    },
    tempData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      list: [
        [
          {
            value: "1",
            label: "1"
          },
          {
            value: "2",
            label: "2"
          },
          {
            value: "2",
            label: "1"
          },
          {
            value: "3",
            label: "3"
          },
          {
            value: "4",
            label: "4"
          },
          {
            value: "5",
            label: "5"
          },
          {
            value: "6",
            label: "6"
          },
          {
            value: "7",
            label: "7"
          },
          {
            value: "8",
            label: "8"
          },
          {
            value: "9",
            label: "9"
          },
          {
            value: "10",
            label: "10"
          },
          {
            value: "11",
            label: "11"
          },
          {
            value: "12",
            label: "12"
          },
          {
            value: "13",
            label: "13"
          },
          {
            value: "14",
            label: "14"
          },
          {
            value: "15",
            label: "15"
          },
          {
            value: "16",
            label: "16"
          },
          {
            value: "17",
            label: "17"
          },
          {
            value: "18",
            label: "18"
          },
          {
            value: "19",
            label: "19"
          },
          {
            value: "20",
            label: "20"
          }
        ],
        [
          {
            value: "-1",
            label: "1"
          },
          {
            value: "-2",
            label: "2"
          },
          {
            value: "-3",
            label: "3"
          },
          {
            value: "-4",
            label: "4"
          },
          {
            value: "-5",
            label: "5"
          },
          {
            value: "-6",
            label: "6"
          },
          {
            value: "-7",
            label: "7"
          },
          {
            value: "-8",
            label: "8"
          },
          {
            value: "-9",
            label: "9"
          }
        ]
      ],
      show: false,
      selectTypeList,
      inputTypeList,
      dateParams: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false,
        timestamp: true
      }
    };
  },
  computed: {
    ...mapGetters(["areaMap"]),
    formKeys() {
      const keys = Object.keys(this.form);
      return keys;
    },
    needDynamicData() {
      let flag = false;
      for (let i = 0; i < this.formKeys.length; i++) {
        const key = this.formKeys[i];
        if (
          this.formConfig[key]["extend"] &&
          this.formConfig[key]["extend"]["dynamic"]
        ) {
          flag = true;
          break;
        }
      }
      return flag;
    }
  },
  watch: {
    tempData: {
      handler(newVal) {
        if (newVal && Object.keys(newVal).length > 0) {
          this.initFormValue();
        }
      },
      immediate: true,
      deep: true
    },
    isShow(val) {
      if (val) {
        this.initFormValue();
      }
    },
    dynamicData: {
      handler(newVal) {
        console.log("dynamicData", newVal);
        if (this.needDynamicData && newVal && Object.keys(newVal).length > 0) {
          this.initFormValue();
        }
      },
      immediate: true,
      deep: true
    }
  },

  methods: {
    onInputFocused(event, key) {
      this.$emit("inputFocused", key);
    },
    confirm(e) {
      console.log(e);
    },
    init() {
      this.initFormValue();
    },
    reset() {
      console.log(123213);
      this.$refs.uForm.resetFields();
    },
    getData() {
      return new Promise((resolve, reject) => {
        this.$refs.uForm.validate(valid => {
          if (valid) {
            const values = { ...this.form };
            if (this.selectMap) {
              const selectMapKeys = Object.keys(this.selectMap);
              if (selectMapKeys.length > 0) {
                for (let i = 0; i < selectMapKeys.length; i++) {
                  values[selectMapKeys[i]] = this.selectMap[selectMapKeys[i]];
                }
              }
            }
            resolve(values);
          } else {
            reject(new Error("数据格式错误"));
          }
        });
      });
    },
    updateValues(tailArr, value) {
      this.$emit("update", tailArr.join("."), value);
    },
    onInputChange(value, fKey) {
      this.updateValues(["form", fKey], value);
    },
    onSelectCancels(value, fKey) {
      this.updateValues(["form", fKey], value);
    },
    onSelectCancel(fKey) {
      this.updateValues(["formConfig", fKey, "visible"], false);
    },
    onDatePickerConfirm(date, fKey) {
      const dateStr = `${date.year}-${date.month}-${date.day}`;
      this.updateValues(["form", fKey], dateStr);
      this.updateValues(["selectMap", fKey], dateStr);
      this.updateValues(["formConfig", fKey, "visible"], false);
    },
    onSelectConfirms(item, fKey) {
      let value = "";
      item.forEach(element => {
        value += element.value;
      });
      this.updateValues(["form", fKey], value);
    },
    onSelectConfirm(item, fKey) {
      this.updateValues(["form", fKey], item[0]["label"]);
      this.updateValues(["selectMap", fKey], item[0]["value"]);
      this.updateValues(["formConfig", fKey, "visible"], false);
    },
    onAreaPickerConfirm(items, fKey) {
      const ids = items.map(item => item.id);
      const labels = items.map(item => item.label);
      this.updateValues(["form", fKey], labels.join("-"));
      this.updateValues(["selectMap", fKey], ids.join(","));
      this.updateValues(["formConfig", fKey, "visible"], false);
    },
    onSelectClicks() {
      this.show = true;
    },
    onSelectClick(fKey) {
      if (fKey === "channelId") {
        this.$emit("inputFocused", fKey);
        return false;
      }
      if (!this.formConfig[fKey].customize.disabled) {
        this.updateValues(["formConfig", fKey, "visible"], true);
      }
    },
    buildAreaList(key) {
      if (
        this.formConfig[key]["extend"] &&
        this.formConfig[key]["extend"]["level"]
      ) {
        return this.formConfig[key]["extend"]["level"] === 2
          ? this.cityList
          : this.areaList;
      }
      return this.cityList;
    },
    buildSelectList(key) {
      if (
        this.formConfig[key]["extend"] &&
        this.formConfig[key]["extend"]["dynamic"]
      ) {
        const dynamicKey = this.formConfig[key]["extend"]["dynamicKey"];
        return this.dynamicData[dynamicKey];
      } else {
        if (this.formConfig[key]["type"] === "autoComplete") {
          return this.formConfig[key]["customize"]["dataSource"].map(item => ({
            value: item.value,
            label: item.text
          }));
        } else {
          return this.formConfig[key]["customize"]["options"];
        }
      }
    },
    // 回填表单值，编辑时使用
    initFormValue() {
      if (this.$refs.uForm && this.$refs.uForm.setRules) {
        this.$refs.uForm.setRules(this.rules);
      }
      for (const fieldKey in this.formConfig) {
        const field = this.formConfig[fieldKey];
        if (this.selectTypeList.includes(field["type"])) {
          if (field.customize && field.customize.options) {
            const temp = field.customize.options.filter(
              item =>
                item.value === this.tempData[fieldKey] ||
                item.value === this.form[fieldKey]
            )[0];
            if (temp) {
              this.updateValues(["selectMap", fieldKey], temp["value"]);
              this.updateValues(["form", fieldKey], temp["label"]);
            }
          } else if (field["extend"] && field["extend"]["dynamic"]) {
            const dynamicKey = field["extend"]["dynamicKey"];
            const temp = this.dynamicData[dynamicKey]
              ? this.dynamicData[dynamicKey].filter(
                  item =>
                    item.value === this.tempData[fieldKey] ||
                    item.value === this.form[fieldKey]
                )[0]
              : null;
            if (temp) {
              this.updateValues(["selectMap", fieldKey], temp["value"]);
              this.updateValues(["form", fieldKey], temp["label"]);
            }
          }
        } else if (field["type"] === "area") {
          const value = this.tempData[fieldKey] || this.form[fieldKey];
          if (value) {
            const ids = value.split(",");
            if (ids.length > 0) {
              const labels = ids.map(id => this.areaMap[id]["name"]);
              this.updateValues(["selectMap", fieldKey], value);
              this.updateValues(["form", fieldKey], labels.join("-"));
            }
          }
        } else if (field["type"] === "date") {
          let value = this.tempData[fieldKey] || this.form[fieldKey];
          if (value) {
            const format =
              this.formConfig[fieldKey]["customize"] &&
              this.formConfig[fieldKey]["customize"]["format"]
                ? this.formConfig[fieldKey]["customize"]["format"]
                : "YYYY-MM-DD";
            value = dayjs(value).format(format);
            this.updateValues(["form", fieldKey], value);
            this.updateValues(["selectMap", fieldKey], value);
          }
        } else {
          const value = this.tempData[fieldKey] || this.form[fieldKey];
          this.updateValues(["form", fieldKey], value);
        }
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.form_warp {
  padding: 0 25px;
  padding-bottom: 110px;
}
</style>
